import java.util.*;
import java.awt.geom.*;

public class Util {
	
	//---------------------------------------------------------------------------
	
	static public Planet findClosestPlanet(PlanetWars pw,Planet source, List<Planet> planetList) {

		Planet dest = null;
		int oldDistance = Integer.MAX_VALUE;
		
		for (Planet P: planetList){
			int newDistance = pw.Distance(source.PlanetID(), P.PlanetID());
			if( newDistance < oldDistance ){
				dest = P;
				oldDistance = newDistance;
			}
		}
		
		return dest;

	} 
	//---------------------------------------------------------------------------
	static public List<RainmanPlanet> findBestPayback(PlanetWars pw, Planet source, int nbPlanet, List<RainmanPlanet> planetList) {
		if(planetList.isEmpty()){
			return null;
		}
		// Calculate distance from source to all planets in list
		for (RainmanPlanet P: planetList){
			P.distance = pw.Distance(source.PlanetID(), P.PlanetID());
		}

		// Sort by Distance
		Collections.sort(planetList, new ComparatorDistance());
		
		// Get closest of nbPlanet
		List <RainmanPlanet> subList = planetList.subList(0, Math.min(planetList.size(), nbPlanet));
		Collections.sort(subList, new ComparatorPayback());
		
		return subList;

	} 
	
	// ---------------------------------------------------------------------------
/*
	static public int calcDistance(Planet s, Planet d){
		Point2D sPos = new Point2D.Double();
		sPos.setLocation(s.X(),s.Y());
		Point2D dPos = new Point2D.Double();
		dPos.setLocation(d.X(),d.Y());
		double distance = sPos.distance( dPos ); 
		return (int)Math.ceil(distance);
	}
	*/
	// ---------------------------------------------------------------------------
	static public boolean callForHelp(PlanetWars pw,RainmanPlanet source,List<RainmanPlanet> planetList){
	
		int shipsNeeded = source.inDangerShipsNeeded;
		
		// Calculate distance from source to all planets in list
		for (RainmanPlanet P: planetList){
			P.distance = pw.Distance(source.PlanetID(), P.PlanetID());
		}
		// Sort by distance so we call help from closest planet
		Collections.sort(planetList, new ComparatorDistance());
		
		// Call
		for (RainmanPlanet P: planetList){
			if ( shipsNeeded > 0 && P.distance > 0 && P.distance <= source.inDangerNbTurn+5 && P.freeShips >0){
				int tmpShips = Math.min(shipsNeeded, P.freeShips);
				pw.IssueOrder(P, source, tmpShips);
				P.freeShips -= tmpShips;
				shipsNeeded -= tmpShips;
			}
		}
		
		return true;
	}
}
